#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题: 打印不合法的文件名
问题: 你的程序获取了一个目录中的文件名列表，但是当它试着去打印文件名的时候程序崩溃， 
    出现了 UnicodeEncodeError 异常和一条奇怪的消息—— surrogates not allowed 。
提示 :
"""

import os
import sys

with open('b\udce4d.txt', 'w') as f:
    f.write('Spicy!')


def recipe1():
    files = os.listdir('.')
    print(f"{files = }")

    for name in files:
        try:
            print(name)
            print(f"{name.encode('utf-8') = }") # UnicodeEncodeError: 'utf-8' codec can't encode character '\udce4' in position 1: surrogates not allowed
        except UnicodeEncodeError:
            print(bad_filename(name))
            print(bad_filename1(name))

def bad_filename(filename):
    return repr(filename)[1:-1]

def bad_filename1(filename):
    '''重新编码'''
    temp = filename.encode(sys.getfilesystemencoding(), errors='surrogateescape')
    return temp.decode('latin-1')

def main():
    print('recipe1'.center(20, '*'))
    recipe1()

if __name__ == '__main__':
    main() 